#pragma once
#include "mythconfig.hh"
#ifdef WIN32
#	include <WinSock2.h>
#	pragma comment(lib,"ws2_32")
typedef int socklen_t;
#else
#	include <wchar.h>
#	include <unistd.h>
#	include <assert.h>
#	include <sys/types.h>
#	include <sys/socket.h>
#	include <arpa/inet.h>
#	include <netinet/in.h>
#	include <time.h>
#	include <unistd.h>
#	include <fcntl.h>
#endif
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <string>
#include <map>
#include "cJSON.h"
#include "SDL.h"
#define HOSTIP "121.42.136.168"
#define HOSTPORT 23584
class VirtualP2PServer
{
public:
	typedef void (OnConnection)(std::string ip, int port, std::string rtmplink,int UdpSock,void* data);
	typedef void (OnRecv)(void* src, int len, void* data);
	typedef std::string (OnGetLink)(void* data);
	static VirtualP2PServer* CreateNew(){
		return new VirtualP2PServer();
	}
	VirtualP2PServer();
	~VirtualP2PServer();
	static int StartThreadStatic(void* data){
		if (data){
			VirtualP2PServer* tmp = (VirtualP2PServer*) data;
			tmp->StartThread();
		}
		return 0;
	}
	void setUserid(int userid){
		g_userid = userid;
	}
	void GetLink(std::string link);
	void SetOnLink(OnGetLink* OnGetLinkCallback, void* data){
		_OnGetLink = OnGetLinkCallback;
		_OnGetLinkData = data;
	}
	void SetOnConnection(OnConnection* OnConnectionCallback, void* data){
		_OnConnection = OnConnectionCallback;
		_onConnectionData = data;
	}
	void SetOnRecvData(OnRecv* OnRecvCallback, void* data){
		_OnRecv = OnRecvCallback;
		_OnRecvData = data;
	}
	void Login(char* username, char* password);
	int Start(int* flag);
	int Stop();
private:
	int InitSock();
	OnConnection* _OnConnection;
	OnRecv* _OnRecv;
	OnGetLink* _OnGetLink;
	void* _OnGetLinkData;
	void* _OnRecvData;
	void* _onConnectionData;
	//stUserListNode* GetUser(char *username);
protected:
	void udpsend(char* ip, int port, cJSON* msg);
	void udpsend(sockaddr_in* addr, cJSON* msg);
	void hostsend(cJSON* msg);
	int StartThread();
#ifdef WIN32
	SOCKET PrimaryUDP;
#else
    int PrimaryUDP;
#endif
	bool mrunning;
	int recv_within_time(int fd, char *buf, size_t buf_n, struct sockaddr* addr, socklen_t *len, unsigned int sec, unsigned usec);
	SDL_Thread* pid;
	int g_userid;
	int* _flag;
};
